package com.kkd.kkdapp.activity;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kkd.kkdapp.Environment;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.Notify.Const;
import com.kkd.kkdapp.Notify.NotifyDispatcher;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.manager.DownFileManager;
import com.kkd.kkdapp.http.manager.DownFileManager.DownLoadCallback;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.AppUtil.onToastDismiss;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.MD5;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

/**
 * html5Web
 * 
 * @author mty
 * 
 */

public class KKDSinaWebActivity extends BaseActivity implements
		OnClickListener, OnKeyListener {

	private static final int TO_LOGIN = 1000;//
	private static final int DOWNLOAD_START = 0;
	private static final int DOWNLOAD_FINISH = 1;
	private static final int DOWNLOAD_PROGRESS = 2;
	public static final int SET_PWD = 1001;
	public static final int SET_PWD_SUCCESS = 1002;
	public static final int SET_PWD_FAITURE = 1003;
	public static final int SET_RECHARGE_SUCCESS = 1004;
	public static final int SET_RECHARGE_FAITURE = 1005;
	public static final int SET_WITHDRAW_SUCCESS = 1006;
	public static final int SET_WITHDRAW_FAITURE = 1007;

	private WebView mWebView;
	private RelativeLayout treat_top_img; // 后退
	private String rootUrl; // web的跟url
	private String amount = "0";
	private String data;
	private String curUrl; // web的当前
	private TextView title_tv; // 标题
	private String titleName; // 标题名
	private ProgressBar web_increase; // 进度条
	private RelativeLayout share; // 分享
	private String shareUrl;
	private String desc = "[快快金融]APP,快快贷致力于打造中国最具专业性的创新型互联网金融综合借贷服务平台 ";
	private RelativeLayout happy_currency_task;
	private boolean useTitleName;
	private boolean useActiveTitle;
	private Dialog shareFailure; // 分享失败Dialog
	private Dialog happyCoinCompleteProgressDialog;
	private String coinMisUrl; // 快乐币任务url
	private boolean flag_onActivityResult = false;// 跳转到登录页面回来时的标记
	private RelativeLayout kkdWeb_tv_howto; // 如何获得
	private RelativeLayout happy_task_bt; // 常见问题
	private Dialog mDialog;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DOWNLOAD_START:

				break;
			case DOWNLOAD_PROGRESS:
				int progress = msg.arg1;
				web_increase.setVisibility(View.VISIBLE);
				web_increase.setProgress(progress);

				break;
			case DOWNLOAD_FINISH:
				String path = msg.obj.toString();
				if (mDialog != null) {
					mDialog.cancel();
					mDialog = null;
				}
				mDialog = DialogUtils.pdfDownLoadDialog(
						KKDSinaWebActivity.this, path);
				mDialog.show();
				PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat(
						"alpha", 1f, 0f);
				ObjectAnimator animator = ObjectAnimator
						.ofPropertyValuesHolder(web_increase, alpha);
				animator.setDuration(1000).start();
				animator.addListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {
					}

					@Override
					public void onAnimationRepeat(Animator animation) {
					}

					@Override
					public void onAnimationEnd(Animator animation) {
						web_increase.setVisibility(View.GONE);
					}

					@Override
					public void onAnimationCancel(Animator animation) {
					}
				});
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_treaty);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |  
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);  
		Intent intent = getIntent();

		rootUrl = intent.getStringExtra("url");
		if (TextUtils.isEmpty(rootUrl)) {
			data = intent.getStringExtra("data");
		}
		if (TextUtils.isEmpty(rootUrl) && TextUtils.isEmpty(data))
			finish();

		amount = intent.getStringExtra("amount");
		curUrl = rootUrl;
		titleName = intent.getStringExtra("titleName");
		shareUrl = intent.getStringExtra("shareUrl");
		desc = intent.getStringExtra("desc");
		useTitleName = intent.getBooleanExtra("useTitleName", false);
		useActiveTitle = intent.getBooleanExtra("useActiveTitle", false);
		mWebView = (WebView) this.findViewById(R.id.treaty_web);
		treat_top_img = (RelativeLayout) this.findViewById(R.id.treat_top_img);
		title_tv = (TextView) this.findViewById(R.id.treat_top_tv);
		web_increase = (ProgressBar) this.findViewById(R.id.web_increase);
		share = (RelativeLayout) this.findViewById(R.id.share);
		happy_currency_task = (RelativeLayout) findViewById(R.id.happy_currency_task);
		if ("".equals(shareUrl) || shareUrl == null) {
			share.setVisibility(View.GONE);
		} else {
			share.setVisibility(View.VISIBLE);
		}
		treat_top_img.setOnClickListener(this);
		share.setOnClickListener(this);
		happy_currency_task.setOnClickListener(this);
		mWebView.setOnKeyListener(this);
		initWeb();
		loadweb();
		coinMisUrl = intent.getStringExtra("coinMisUrl");
		LogUtil.e("TAG", "coinMisUrl--->" + coinMisUrl);
		kkdWeb_tv_howto = (RelativeLayout) this
				.findViewById(R.id.kkdWeb_tv_howto);
		kkdWeb_tv_howto.setOnClickListener(this);
		happy_task_bt = (RelativeLayout) this.findViewById(R.id.happy_task_bt);
		happy_task_bt.setOnClickListener(this);
	}

	/**
	 * initWeb:(初始化webview 设置).
	 * 
	 * @author askzhao
	 */
	private void initWeb() {
		WebSettings webSettings = mWebView.getSettings();
		// 设置WebView属性，能够执行Javascript脚本
		webSettings.setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		// 设置可以访问文件
		webSettings.setAllowFileAccess(true);
		// 设置支持缩放
		webSettings.setBuiltInZoomControls(true);
		webSettings.setDomStorageEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		// 设置Web视图
		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
				} else if (url.startsWith("http:") || url.startsWith("https:")) {
					if ("http://www.kuaikuaidai.com/handle_withhold_authority/return_url/deposit"
							.equals(url)) {// 充值
						requestRechargeSuccessActive();
					} else if ("http://www.kuaikuaidai.com/handle_withhold_authority/return_url/withdraw"
							.equals(url)) {// 提现
						KKDSinaWebActivity.this
								.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
						finish();
					} else if ("http://www.kuaikuaidai.com/handle_withhold_authority/return_url"
							.equals(url)) {// 其他
						KKDSinaWebActivity.this
								.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
						finish();
					} else {
						view.loadUrl(url);
					}

				}
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				// mWebView.loadUrl("file:///android_asset/rate.html");
			};

			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed();
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (flag_onActivityResult) {
					flag_onActivityResult = false;
					mWebView.clearHistory();
				}
				mWebView.loadUrl("javascript:(function() { var videos = document.getElementsByTagName('video'); for(var i=0;i<videos.length;i++){videos[i].play();}})()");
				curUrl = url;
				String title = view.getTitle();
				if (useTitleName) {
					if (titleName != null) {
						title_tv.setText(titleName);
					}
				} else {
					title_tv.setText(title);
				}
				if (useActiveTitle) {
					title_tv.setText("活动公告");
				}
				if ("快乐商城".equals(title)) {
					if (TextUtils.isEmpty(coinMisUrl)) {
						happy_currency_task.setVisibility(View.GONE);
						kkdWeb_tv_howto.setVisibility(View.VISIBLE);
					} else {
						happy_currency_task.setVisibility(View.VISIBLE);
						kkdWeb_tv_howto.setVisibility(View.GONE);
					}
				} else {
					happy_currency_task.setVisibility(View.GONE);
					kkdWeb_tv_howto.setVisibility(View.GONE);
				}
				if ("快乐币任务".equals(title)) {
					happy_task_bt.setVisibility(View.VISIBLE);
				} else {
					happy_task_bt.setVisibility(View.GONE);
				}

			}
		});
		mWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				web_increase.setVisibility(View.VISIBLE);
				web_increase.setProgress(newProgress);
				if (newProgress == 100) {
					PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat(
							"alpha", 1f, 0f);
					ObjectAnimator animator = ObjectAnimator
							.ofPropertyValuesHolder(web_increase, alpha);
					animator.setDuration(1000).start();
					animator.addListener(new AnimatorListener() {

						@Override
						public void onAnimationStart(Animator animation) {
						}

						@Override
						public void onAnimationRepeat(Animator animation) {
						}

						@Override
						public void onAnimationEnd(Animator animation) {
							web_increase.setVisibility(View.GONE);
						}

						@Override
						public void onAnimationCancel(Animator animation) {
						}
					});
				}
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				super.onReceivedTitle(view, title);
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		mWebView.onResume();
	}

	public void loadweb() {

		mWebView.clearHistory();

		// 加载需要显示的网页
		if (!TextUtils.isEmpty(rootUrl)) {
			if (!TextUtils.isEmpty(amount)) {
				String postdata = "";
				postdata = "amount=" + amount;
				mWebView.loadUrl(rootUrl + "&" + postdata);
			} else {
				mWebView.loadUrl(rootUrl);

			}
		} else {
			if (!TextUtils.isEmpty(data)) {
				mWebView.loadData(data, "text/html", "utf-8");
			}
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.treat_top_img: // 后退
			finish();
			break;

		case R.id.happy_currency_task: // 快乐币任务
			Intent intent = new Intent(KKDSinaWebActivity.this,
					KKDSinaWebActivity.class);
			intent.putExtra("url", coinMisUrl);
			startActivity(intent);
			finish();
			break;

		case R.id.share:
			String tile = "快快贷理财";
			String tip = "[快快金融]APP,快快贷致力于打造中国最具专业性的创新型互联网金融综合借贷服务平台 ";
			if (!TextUtils.isEmpty(titleName)) {
				tile = titleName;
			}
			if (!TextUtils.isEmpty(desc)) {
				tip = desc;

			}

			break;
		case R.id.kkdWeb_tv_howto: // 如何获得
			intent = new Intent(KKDSinaWebActivity.this,
					HowToHappyCoinActivity.class);
			startActivity(intent);
			break;
		case R.id.happy_task_bt: // 快乐币任务常见问题
			intent = new Intent(KKDSinaWebActivity.this,
					KKDSinaWebActivity.class);
			intent.putExtra("url", Environment.getH5Url()
					+ "/appIconques.html?channel=Android");
			startActivity(intent);
			break;
		}
	}

	@Override
	protected void onPause() {

		super.onPause();
		mWebView.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		web_increase.setProgress(0);
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
		}
		if (shareFailure != null) {
			shareFailure.cancel();
			shareFailure = null;
		}
		shareResult = -1;
		PreferenceUtils.getInstance().clearSharePrefernces(
				KKDSinaWebActivity.this);
		if (happyCoinCompleteProgressDialog != null) {
			happyCoinCompleteProgressDialog.cancel();
			happyCoinCompleteProgressDialog = null;
		}

		if (dialog_newtask != null) {
			dialog_newtask.cancel();
			dialog_newtask = null;
		}
		if (dialog_fail != null) {
			dialog_fail.cancel();
			dialog_fail = null;
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (v.getId()) {
			case R.id.treaty_web:
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					finish();
					return true;
				}
				break;
			}
		}

		return false;
	}

	private MediaPlayer mediaPlayer;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == TO_LOGIN) {
			if (resultCode == LoginActivity.LOGIN_SUCCESS) {
				flag_onActivityResult = true;
				loadweb();
			} else {
				if (TextUtils.isEmpty(mWebView.getUrl())) {
					finish();
				}
			}
		}

	}

	private Dialog dialog_newtask;
	private Dialog dialog_fail;

	/**
	 * 充值成功后请求的活动接口
	 */
	private void requestRechargeSuccessActive() {
		String customertAndToken = PreferenceUtils.getInstance().getcustomerId(
				this);
		String[] cat = customertAndToken.split("&");
		if (cat == null || cat.length < 2) {
			KKDSinaWebActivity.this
					.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
			finish();
			return;
		}
		KkdHttpMagager.getInstance().rechargeSinaPayActive(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						String result = responseBody.toString();
						try {
							if (TextUtils.isEmpty(result)
									|| "null".equals(result)) {
								AppUtil.makeToastForCustomer(
										KKDSinaWebActivity.this, "充值成功",
										new onToastDismiss() {

											@Override
											public void onToastDismiss() {
												KKDSinaWebActivity.this
														.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
												finish();
											}
										});
							} else {
								JSONObject jsonObject = new JSONObject(result);
								JSONObject jsonObject_depositTips = jsonObject
										.optJSONObject("depositTips");
								String couTopDesc = jsonObject_depositTips
										.optString("couTopDesc");
								String couAmount = jsonObject_depositTips
										.optString("couAmount");
								String couponCount = jsonObject_depositTips
										.optString("couponCount");
								if (!TextUtils.isEmpty(couAmount)
										&& !TextUtils.isEmpty(couTopDesc)) { // 说明有新手红包
									if (dialog_newtask != null) {
										dialog_newtask.cancel();
										dialog_newtask = null;
									}
									dialog_newtask = DialogUtils
											.finishFirstRechargeDialog(
													KKDSinaWebActivity.this,
													couTopDesc,
													couAmount,
													couponCount,
													new OnSingleClickListener() {

														@Override
														public void onSingleClick(
																View v) {
															if (dialog_newtask != null) {
																dialog_newtask
																		.cancel();
																dialog_newtask = null;
															}
															Intent intent = new Intent(
																	KKDSinaWebActivity.this,
																	HomeActivity.class);
															startActivity(intent);
															HomeActivity.mActivity
																	.homeNavigation();
															KKDSinaWebActivity.this
																	.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
															finish();
															PreferenceUtils
																	.getInstance()
																	.setMyproperty(
																			KKDSinaWebActivity.this,
																			"");
														}
													});
									dialog_newtask.show();
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						if (statusCode == 265) {
							if (dialog_fail != null) {
								dialog_fail.cancel();
								dialog_fail = null;
							}
							dialog_fail = DialogUtils.communalDialog1(
									KKDSinaWebActivity.this, desc, "我知道了",
									new OnSingleClickListener() {

										@Override
										public void onSingleClick(View v) {
											if (dialog_fail != null) {
												dialog_fail.cancel();
												dialog_fail = null;
											}
										}
									});
							dialog_fail.show();
							dialog_fail
									.setOnCancelListener(new OnCancelListener() {

										@Override
										public void onCancel(
												DialogInterface dialog) {
											KKDSinaWebActivity.this
													.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
											finish();
										}
									});
						} else {
							KKDSinaWebActivity.this
									.setResult(KKDSinaWebActivity.SET_PWD_SUCCESS);
							finish();
						}
					}
				});
	}
}
